from django_redis import get_redis_connection
from rest_framework import serializers
from users.models import User
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_email
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS
from django.conf import settings


class UserSerializer(serializers.ModelSerializer):
    # allow:"true"
    # mobile:"13810736100"
    # password:"weiran1988"
    # password2:"weiran1988"
    # sms_code:"432146"
    # username:"weiran"
    allow = serializers.CharField(write_only=True)
    password2 = serializers.CharField(max_length=20, min_length=6, write_only=True)
    sms_code = serializers.CharField(write_only=True, max_length=6, min_length=6)

    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ("username", "password", "password2", "mobile", "allow", "sms_code", "id","token")
        extra_kwargs = {
            'password': {'max_length': 20, 'min_length': 8, "write_only": True},
            'username': {'max_length': 20, 'min_length': 5}
        }

    def validate(self, attrs):
        if attrs["password"] != attrs['password2']:
            raise serializers.ValidationError("两次密码不一致")
        return attrs

    def validate(self, attrs):
        red =  get_redis_connection("sms_code")
        num = red.get(attrs["mobile"]).decode('utf-8')
        print(num)
        print(attrs["sms_code"])
        if attrs["sms_code"] != num:
            raise serializers.ValidationError("验证码有误")
        return attrs

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError("请勾选协议")
        return value

    def create(self, validated_data):
        # del validated_data["sms_code"]
        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'], mobile=validated_data['mobile'])
        # User.set_password(validated_data['password'])
        # user.save()


        # 生成jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user


class UserIndexSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ("username", "mobile", "email", "id", "email_active")


class UserEmailSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def update(self, instance, validated_data):
        # 在django.core.mail模块提供了send_mail来发送邮件。
        # send_mail(subject, message, from_email, recipient_list, html_message=None)
        # subject         邮件标题
        # message         普通邮件正文， 普通字符串
        # from_email      发件人
        # recipient_list  收件人列表
        # html_message    多媒体邮件正文，可以是html字符串

        # message = msg='<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">点击激活</a>'
        # subject = "美多商城邮箱验证"
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
        # send_mail(subject, "", settings.EMAIL_FROM, [to_email], html_message=html_message)

        # 加密token
        tjwss = TJWSS(settings.SECRET_KEY, 300)
        token = tjwss.dumps(instance.username).decode()

        to_email = validated_data['email']
        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token="+token

        send_email.delay(to_email,verify_url)

        instance.email = validated_data['email']
        instance.save()
        return instance




